<?php
/**
 * Created by PhpStorm.
 * User: DELL-PC
 * Date: 2018/8/17
 * Time: 16:46
 */

namespace J\Schema\Collection\Element;


use J\Schema\IElement;
use J\Schema\Collection\ICollection;
use J\Schema\Syntax;

class ElementFactory
{
    protected $types = [];

    /**
     * @param ICollection $c
     * @param string $name
     * @param array $schema
     * @return IElement
     */
    public function create($c, $name, $schema = [])
    {
        if ($name === Syntax::KEY_STATUS) {
            $schema = [
                Syntax::KEY_TYPE => Syntax::VALUE_INT | Syntax::MASK_NOT_NULL,
                'label'   => '状态',
                'holder' => 'switch',
                'display' => function ($v) { return $v > 0; },
            ];
        } elseif ($name === Syntax::KEY_ID) {
            $schema = [
                Syntax::KEY_TYPE => Syntax::FIELD_ID,
            ];
        } else {
            $schema = $this->getRealSchema($schema);
        }

        // 隶属列
        if($schema[Syntax::KEY_TYPE] & Syntax::LINK_BLS){
            $schema[Syntax::KEY_TYPE] =  Syntax::FIELD_BLS;
            return new BelongsElement($name, $schema, $c);
        }
        // 多项选择列
        if($schema[Syntax::KEY_TYPE] & Syntax::MASK_MULTI){
            return new MultiSelectElement($name, $schema, $c);
        }

        return new Element($name, $schema, $c);
    }

    protected function getRealSchema($schema)
    {
        if (isset($schema[Syntax::KEY_BASE])) {
            $base = $this->getGeneralSchemaByBase($schema[Syntax::KEY_BASE]);
            // type属性合并
            if(isset($base[Syntax::KEY_TYPE])){
                $type = array_isset($schema,Syntax::KEY_TYPE, 0);
                $schema[Syntax::KEY_TYPE] = $type | $base[Syntax::KEY_TYPE];
                unset($base[Syntax::KEY_TYPE]);
            }

            //自定义属性优先
            return array_merge($base,$schema);
        }
        return $schema;
    }

    protected function getGeneralSchemaByBase($id)
    {
        return array_isset($this->types, $id, []);
    }

    public function setConfig($config)
    {
        $this->types = $config;
    }
}